import webapp2
import jinja2
import os
from google.appengine.api import users
import logging
import era
import country

import spreadsheet
from google.appengine.ext import ndb
import dic
import geo
import labelcat



jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))


class LanguagePage(webapp2.RequestHandler):
    def get(self):
        template_values = {
        }  
        template = jinja_environment.get_template("game-language.html")
        self.response.out.write(template.render(template_values))

        
class LanguageChange(webapp2.RequestHandler):
    def post(self):
        lang = self.request.get("language")
        logging.info("lang=" + lang)
        self.redirect("/" + lang + "/game")

      
class Index(webapp2.RequestHandler):
    def get(self, lang):
        templateName = ""
        url = ""
        url_linktext = ""
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
            templateName = 'game.html'
            instance = dic.Operation()
            operation_label_map = {}
            dics = instance.getDics(lang, labelcat.Cat.ARCHIVE_OPERATION)
            for dic_entity in dics:
                operation_label_map[dic_entity.name] = dic_entity.label
            game_label_map = {}
            dics = instance.getDics(lang, labelcat.Cat.Game) 
            for dic_entity in dics:
                game_label_map[dic_entity.name] = dic_entity.label
            
            template_values = {
              'user':users.get_current_user().email(),
              'url': url,
              'url_linktext': url_linktext,
              'lang':lang,
              'gameLabels':game_label_map,
              'operationLabels':operation_label_map

            }  
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'
            templateName = 'login.html'

            template_values = {
              'url': url,
              'url_linktext': url_linktext,
              'lang':lang,
            }  

        template = jinja_environment.get_template(templateName)
 
        self.response.out.write(template.render(template_values))
        
class InitEra(webapp2.RedirectHandler):
    def get(self):
        spreadsheet_operation = spreadsheet.Operation()
        spreadsheet_feed = spreadsheet_operation.getFeed();
        gd_client = spreadsheet_operation.gd_client;
        # clean data
        eras = era.Era.query()
        for era_element in eras:
            era_element.key.delete()

        for i, spreadsheet_entry in enumerate(spreadsheet_feed.entry):
            spreadsheet_title = spreadsheet_entry.title.text
            
            if "UDATA-ERA" == spreadsheet_title:
                spreadsheet_id_parts = spreadsheet_entry.id.text.split('/')
                spreadsheet_id = spreadsheet_id_parts[len(spreadsheet_id_parts) - 1]                
                worksheet_feed = gd_client.GetWorksheetsFeed(spreadsheet_id);
                for j, worksheet_entry in enumerate(worksheet_feed.entry):
                    worksheet_title = worksheet_entry.title.text
                    worksheet_id_parts = worksheet_entry.id.text.split('/')
                    worksheet_id = worksheet_id_parts[len(worksheet_id_parts) - 1]                  
                    logging.info("=======worksheet title:" + worksheet_title)
                    list_feed = gd_client.GetListFeed(spreadsheet_id, worksheet_id)
                    for  k, list_entry in enumerate(list_feed.entry):
                        era_name = list_entry.custom["name"].text
                        start = int(list_entry.custom["start"].text)
                        desc = list_entry.custom["desc"].text
                        era_key = ndb.Key("Era", era_name)
                        era_entity = era.Era(key=era_key, name=era_name, start=start)              
                        era_entity.put()         
                        
class InitCountry(webapp2.RedirectHandler):
    def get(self):
        spreadsheet_operation = spreadsheet.Operation()
        spreadsheet_feed = spreadsheet_operation.getFeed();
        gd_client = spreadsheet_operation.gd_client;
        # clean data
        countries = country.CountrySys.query()
        for country_element in countries:
            country_element.key.delete()
        for i, spreadsheet_entry in enumerate(spreadsheet_feed.entry):
            spreadsheet_title = spreadsheet_entry.title.text
            if spreadsheet_title.startswith("UDATA-COUNTRY"):
                country_era = spreadsheet_title[14:]
                logging.info("Country era:"+country_era)
                spreadsheet_id_parts = spreadsheet_entry.id.text.split('/')
                spreadsheet_id = spreadsheet_id_parts[len(spreadsheet_id_parts) - 1]
                worksheet_feed = gd_client.GetWorksheetsFeed(spreadsheet_id);
                for j, worksheet_entry in enumerate(worksheet_feed.entry):
                    worksheet_title = worksheet_entry.title.text
                    worksheet_id_parts = worksheet_entry.id.text.split('/')
                    worksheet_id = worksheet_id_parts[len(worksheet_id_parts) - 1]
                    logging.info("======Country:" + worksheet_title)
                    list_feed = gd_client.GetListFeed(spreadsheet_id, worksheet_id)
                    for k, list_entry in enumerate(list_feed.entry):
                        country_name = list_entry.custom["name"].text
                        country_key = ndb.Key("CountrySys", country_name + "_" + country_era)
                        culture = list_entry.custom["culture"].text
                        style = list_entry.custom["style"].text
                        country_entity = country.CountrySys(key=country_key, name=country_name, culture=culture, style=style, era=country_era)              
                        country_entity.put()
        

class InitDictionaryEn(webapp2.RedirectHandler):
    def get(self):
        spreadsheet_operation = spreadsheet.Operation()
        spreadsheet_feed = spreadsheet_operation.getFeed();
        gd_client = spreadsheet_operation.gd_client;
        # clean data
        dictionaries = dic.Dic.query(dic.Dic.lang == "en")
        for dictionary_element in dictionaries:
            dictionary_element.key.delete()
    
        for i, spreadsheet_entry in enumerate(spreadsheet_feed.entry):
            spreadsheet_title = spreadsheet_entry.title.text
            
            if "UDATA-LABEL-EN" == spreadsheet_title :
                spreadsheet_id_parts = spreadsheet_entry.id.text.split('/')
                spreadsheet_id = spreadsheet_id_parts[len(spreadsheet_id_parts) - 1]                
                worksheet_feed = gd_client.GetWorksheetsFeed(spreadsheet_id);
                for j, worksheet_entry in enumerate(worksheet_feed.entry):
                    worksheet_title = worksheet_entry.title.text
                    dic_cat = worksheet_title
                    worksheet_id_parts = worksheet_entry.id.text.split('/')
                    worksheet_id = worksheet_id_parts[len(worksheet_id_parts) - 1]                  
                    logging.info("=======worksheet title:" + worksheet_title)
                    list_feed = gd_client.GetListFeed(spreadsheet_id, worksheet_id)
                    for  k, list_entry in enumerate(list_feed.entry):
                        dic_name = list_entry.custom["name"].text  
                        dic_lang = list_entry.custom["lang"].text
                        dic_label = list_entry.custom["label"].text
                        dic_entity = dic.Dic(name=dic_name, lang=dic_lang, label=dic_label, cat=dic_cat)
                        dic_entity.put()
                        
class InitDictionaryCn(webapp2.RedirectHandler):
    def get(self):
        spreadsheet_operation = spreadsheet.Operation()
        spreadsheet_feed = spreadsheet_operation.getFeed();
        gd_client = spreadsheet_operation.gd_client;
        # clean data
        dictionaries = dic.Dic.query(dic.Dic.lang == "cn")
        for dictionary_element in dictionaries:
            dictionary_element.key.delete()
    
        for i, spreadsheet_entry in enumerate(spreadsheet_feed.entry):
            spreadsheet_title = spreadsheet_entry.title.text
            
            if "UDATA-LABEL-CN" == spreadsheet_title :
                spreadsheet_id_parts = spreadsheet_entry.id.text.split('/')
                spreadsheet_id = spreadsheet_id_parts[len(spreadsheet_id_parts) - 1]                
                worksheet_feed = gd_client.GetWorksheetsFeed(spreadsheet_id);
                for j, worksheet_entry in enumerate(worksheet_feed.entry):
                    worksheet_title = worksheet_entry.title.text
                    dic_cat = worksheet_title
                    worksheet_id_parts = worksheet_entry.id.text.split('/')
                    worksheet_id = worksheet_id_parts[len(worksheet_id_parts) - 1]                  
                    logging.info("=======worksheet title:" + worksheet_title)
                    list_feed = gd_client.GetListFeed(spreadsheet_id, worksheet_id)
                    for  k, list_entry in enumerate(list_feed.entry):
                        dic_name = list_entry.custom["name"].text  
                        dic_lang = list_entry.custom["lang"].text
                        dic_label = list_entry.custom["label"].text
                        dic_entity = dic.Dic(name=dic_name, lang=dic_lang, label=dic_label, cat=dic_cat)
                        dic_entity.put()
                        
class InitGeo(webapp2.RedirectHandler):
    def get(self):
        spreadsheet_operation = spreadsheet.Operation()
        spreadsheet_feed = spreadsheet_operation.getFeed();
        gd_client = spreadsheet_operation.gd_client;
        # clean data
        geos = geo.Geo.query()
        for element in geos:
            element.key.delete()
    
        for i, spreadsheet_entry in enumerate(spreadsheet_feed.entry):
            spreadsheet_title = spreadsheet_entry.title.text
            
            if "UDATA-GEO" == spreadsheet_title:
                spreadsheet_id_parts = spreadsheet_entry.id.text.split('/')
                spreadsheet_id = spreadsheet_id_parts[len(spreadsheet_id_parts) - 1]                
                worksheet_feed = gd_client.GetWorksheetsFeed(spreadsheet_id);
                for j, worksheet_entry in enumerate(worksheet_feed.entry):
                    worksheet_title = worksheet_entry.title.text
                    geo_cat = worksheet_title
                    worksheet_id_parts = worksheet_entry.id.text.split('/')
                    worksheet_id = worksheet_id_parts[len(worksheet_id_parts) - 1]                  
                    logging.info("=======worksheet title:" + worksheet_title)
                    list_feed = gd_client.GetListFeed(spreadsheet_id, worksheet_id)
                    for  k, list_entry in enumerate(list_feed.entry):
                        lat = float(list_entry.custom["lat"].text)
                        long = float(list_entry.custom["long"].text)
                        type = list_entry.custom["type"].text
                        point = ndb.GeoPt(lat, long)
                        geo_entity = geo.Geo(point=point, type=type)
                        geo_entity.put()
